
#include "AgentGenome.h"
#include "AgentPopulation.h"
#include "GameManager.h"

void AgentPopulation::EvaluatePop(GAPopulation& population) {
    for(int i = 0; i < population.size(); i++) {
        AgentGenome& challenger = dynamic_cast<AgentGenome&>(population.individual(i));
        Agent31* challengerAgent = challenger.buildAgent(0);
        int numMatches = (int) (AgentPopulation::matchPct * population.size());
        for (int j = 0; j < numMatches; j++) {
            AgentGenome& opponent = dynamic_cast<AgentGenome&>(population.individual((rand() % population.size())));
            Agent31* opponentAgent = opponent.buildAgent(1);
            MatchStatistics statistics = AgentPopulation::playMatch(challengerAgent, opponentAgent);
            challenger.recordMatch((statistics.loser != 0), statistics.score[0], statistics.score[1], (float) (statistics.score[0]-statistics.initScore[0]) / statistics.rounds);
            opponent.recordMatch((statistics.loser != 1), statistics.score[1], statistics.score[0], (float) (statistics.score[1]-statistics.initScore[1]) / statistics.rounds);
            delete opponentAgent;
        }
        delete challengerAgent;
    }
    for(int i = 0; i < population.size(); i++) {
        population.individual(i).evaluate(gaTrue);
    }
}

MatchStatistics AgentPopulation::playMatch(Agent31* player1, Agent31* player2) {
    Player* playerArray[2];
    playerArray[0] = dynamic_cast<Player*>(player1);
    playerArray[1] = dynamic_cast<Player*>(player2);
    GameManager game(playerArray);
    game.run();
    return game.getMatchStatistics();
}
